package system

import (
	"cubeAdmin/common"
	"cubeAdmin/common/utils/gconv"
	"cubeAdmin/controllers"
	"cubeAdmin/models"
	"encoding/json"
	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/core/validation"
)

// DictDetailController 字典详情api
type DictDetailController struct {
	controllers.BaseController
}

func (c *DictDetailController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Put", c.Put)
	c.Mapping("Delete", c.Delete)
}

// GetAll @Title 获取字典详情列表
// @Description 获取字典详情列表
// @Success 200 {object} controllers.Result
// @router / [get]
func (c *DictDetailController) GetAll() {
	dictId, _ := c.GetInt64("dictId")
	total, list := models.GetAllDictDetail(c.GetParams(), dictId)
	c.PageTable(gconv.Int64(total), list)
}

// Add 字典值添加页面
// @router /add [get]
func (c *DictDetailController) Add() {
	dictId, err := c.GetInt64("dictId")
	if err != nil {
		c.Fail(err.Error(), common.MsgErr)
	}
	dict, e := models.GetDictById(dictId)
	if e != nil {
		c.Fail(err.Error(), common.DatabaseOperationErr)
	}
	c.Data["dict"] = dict
	c.Data["title"] = "新增字典值"
	c.TplName = "system/dict/data/add.tpl"
}

// Post @Title 添加字典详情
// @Description 添加字典详情
// @Success 200 {object} controllers.Result
// @router / [post]
func (c *DictDetailController) Post() {
	var model models.SysDictDetail
	valid := validation.Validation{}
	json.Unmarshal(c.Ctx.Input.RequestBody, &model)
	logs.Debug(model)
	b, _ := valid.Valid(&model)
	if !b {
		for _, err := range valid.Errors {
			c.Fail(err.Message, common.ArgsValidErr)
		}
	}
	_, e := models.AddDictDetail(&model)
	if e != nil {
		c.Fail(e.Error(), common.DatabaseOperationErr)
	}
	c.Ok("操作成功")
}

// Edit 跳转到部门编辑
// @router /edit [get]
func (c *DictDetailController) Edit() {
	Id, _ := c.GetInt64("id")
	dictDetail, _ := models.GetDictDetailById(Id)
	c.Data["title"] = "字典详情修改"
	c.Data["dictDetail"] = dictDetail
	c.TplName = "system/dict/data/edit.tpl"
}

// Put @Title 修改字典详情
// @Description 修改字典详情
// @Success 200 {object} controllers.Result
// @router / [put]
func (c *DictDetailController) Put() {
	var model models.SysDictDetail
	valid := validation.Validation{}
	json.Unmarshal(c.Ctx.Input.RequestBody, &model)
	b, _ := valid.Valid(&model)
	if !b {
		for _, err := range valid.Errors {
			c.Fail(err.Message, common.ArgsValidErr)
		}
	}
	e := models.UpdateByDictDetail(&model)
	if e != nil {
		c.Fail(e.Error(), common.DatabaseOperationErr)
	}
	c.Ok("操作成功")
}

// Delete @Title 删除字典详情
// @Description 删除字典详情
// @Success 200 {object} controllers.Result
// @router /:id [delete]
func (c *DictDetailController) Delete() {
	id, _ := c.GetInt64(":id", 1)
	e := models.DelByDictDetail(id)
	if e != nil {
		c.Fail(e.Error(), common.DatabaseOperationErr)
	}
	c.Ok("操作成功")
}
